package com.globalwave.pos.inventory.service;

import com.globalwave.pos.inventory.entity.InventoryPeriod;
import com.globalwave.pos.inventory.entity.InventorySO;



public class InventoryPeriodBalanceBO extends InventoryBaseBO {
	

	
	private InventoryPeriodBO inventoryPeriodBO ;
	private InventoryBalanceBO inventoryBalanceBO ;

	public void snapshot()throws Exception {
		InventoryPeriodBO inventoryPeriodBO = getInventoryPeriodBO() ;

		InventoryPeriod currentPeriod = inventoryPeriodBO.current() ;

		getInventoryBalanceBO().archiveCurrentPeriod(currentPeriod) ;
		
		// copy balance
		moveBalancesToPeriod(currentPeriod) ;
		
		inventoryPeriodBO.closeAndOpenNext(currentPeriod) ;
	}
	
	private void moveBalancesToPeriod(InventoryPeriod currentPeriod) throws Exception {
		jdbcDao.executeName("inventory:moveBalancesToPeriod", currentPeriod) ;
	}
	
	/**
	 * 根据Transaction的信息，修复过去的Period Balance
	 * 
	 * @throws Exception
	 */
	public void fix() throws Exception {
		InventorySO inventorySO = (InventorySO)jdbcDao.findName("inventory:maxInventoryTransactionId", null, InventorySO.class) ;
		
		long min = inventorySO.getMin() ;
		long max = inventorySO.getMax() ;
		long id = min ;
		
		while (id < max) {
			// 作stock onhand的init
			initPeriodBalanceFromTransaction(inventorySO) ;
			// 把数量加回过去的period
			sumTransactionsToPeriodBalance(inventorySO) ;
			
			inventoryBalanceBO.archiveCurrentPeriod() ;
		}
	}

	private void initPeriodBalanceFromTransaction(InventorySO inventorySO) throws Exception {
		jdbcDao.executeName("inventory:initPeriodBalanceFromTransaction", inventorySO) ;
	}
	private void sumTransactionsToPeriodBalance(InventorySO inventorySO) throws Exception {
		jdbcDao.executeName("inventory:sumTransactionsToPeriodBalance", inventorySO) ;
	}

	public InventoryPeriodBO getInventoryPeriodBO() {
		if (inventoryPeriodBO == null) {
			inventoryPeriodBO = new InventoryPeriodBO() ;
		}
		return inventoryPeriodBO;
	}

	public void setInventoryPeriodBO(InventoryPeriodBO inventoryPeriodBO) {
		this.inventoryPeriodBO = inventoryPeriodBO;
	}

	public InventoryBalanceBO getInventoryBalanceBO() {
		if (inventoryBalanceBO == null) {
			inventoryBalanceBO = new InventoryBalanceBO(this.warehouseCode) ;
		}
		return inventoryBalanceBO;
	}

	public void setInventoryBalanceBO(InventoryBalanceBO inventoryBalanceBO) {
		this.inventoryBalanceBO = inventoryBalanceBO;
	}
}
